package cn.qu.dockman.mgr.ws.exec;

import cn.qu.dockman.mgr.disparte.ArgDef;
import cn.qu.dockman.mgr.disparte.DispartMgr;
import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.entity.Network;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.mgr.service.NetworkService;
import cn.qu.dockman.protocol.command.Command;
import cn.qu.dockman.protocol.command.client.NetworkListCommand;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.qu.dockman.protocol.command.client.NetworkListCommand.NetworkBody;

/**
 * Created by zh on 17/3/17.
 */
public class NetworkListCommandParser extends CommandParser {

    private DispartMgr dispartMgr;
    private NetworkService networkService;
    private HostService hostService;

    @Override
    public void before() {
        this.dispartMgr = getApplicationContext().getBean(DispartMgr.class);
        this.networkService = getApplicationContext().getBean(NetworkService.class);
        this.hostService = getApplicationContext().getBean(HostService.class);
    }

    @Override
    public void parse(Command command) {

        NetworkListCommand cmd = (NetworkListCommand) command;

        Host host = this.hostService.findByIp(this.getHost());
        if(host == null) return;
        List<Network> networkList = this.networkService.findByHostId(host.getId());

        Map<String, Network> networkMap = new HashMap<>();

        networkList.forEach(network -> networkMap.put(network.getNetworkId(), network));
        NetworkBody[] bodys = cmd.getBody();

        for (NetworkBody body : bodys) {
            if (networkMap.containsKey(body.getId())) {
                networkMap.remove(body.getId());
            }

            ArgDef def = new ArgDef(NetworkListCommand.NAME, this.getHost(), this.getPort(),this.getHostname());
            def.setData(body);

            dispartMgr.notifyObservers(def);
        }

        networkMap.forEach((key, value) -> networkService.delete(value));
    }
}
